package com.atwj.controller;

import com.atwj.Service.OrderService;
import com.atwj.Service.impl.OrderServiceImpl;
import com.atwj.entity.Cart;
import com.atwj.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 吴先森
 * @description: 购物车结账
 * @create 2022-04-01 20:27
 */
public class OrderServlet extends BaseServlet {
    OrderService orderService = new OrderServiceImpl();

    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取 Cart 购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        // 获取 Userid
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser == null) {
            //如果未登录则跳转登陆页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            return;
        }
        Integer userId = loginUser.getId();
        //调用 orderService.createOrder(Cart,Userid);生成订单
        String orderId = orderService.createOrder(cart, userId);
        req.getSession().setAttribute("orderId", orderId);
        //重定向至结账成功页面
        /* req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req,resp);*/
        resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");
    }
}
